// request.js 完整修改
import axios from 'axios';

// 创建自定义适配器
const uniAdapter = config => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: config.baseURL + config.url,
      method: config.method.toUpperCase(),
      data: config.data,
      header: config.headers,
      dataType: config.dataType || 'json',
      responseType: config.responseType || 'text',
      success: res => {
        const response = {
          data: res.data,
          status: res.statusCode,
          statusText: res.errMsg,
          headers: res.header,
          config: config
        };
        resolve(response);
      },
      fail: err => {
        reject(err);
      }
    });
  });
};

// 创建axios实例，并使用自定义适配器
const service = axios.create({
  baseURL: 'http://localhost:8080', // 统一的API前缀，添加 /user
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  adapter: uniAdapter // 使用自定义适配器
});

// 请求拦截器 - 完善Token设置
service.interceptors.request.use(
  config => {
    const token = uni.getStorageSync('token');
    if (token) {

      config.headers['Authorization'] =token;
    }
    return config;
  },
  error => {
    console.error('请求拦截失败:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器 - 增强错误处理
service.interceptors.response.use(
  response => {
    // 假设后端返回格式为 {code: 200, message: '成功', data: {}}
    if (response.data.code && response.data.code != 200) {
		
      uni.showToast({
        title: response.data.message || '请求失败',
        icon: 'none'
      });

      // 401未授权处理
      if (response.data.code === 401) {
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
        uni.showModal({
          title: '登录过期',
          content: '您的登录已过期，请重新登录',
          showCancel: false,
          success: () => {
            uni.reLaunch({
              url: '/pages/login/login' // 跳转到登录页
            });
          }
        });
      }
      return Promise.reject(new Error(response.data.message || '请求失败'));
    } else {
      return response.data;
    }
  },
  error => {
    let errorMsg = '网络错误，请稍后再试';
    if (error.response) {
      switch (error.response.status) {
        case 401:
          errorMsg = '未授权，请登录';
          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');
          uni.reLaunch({
            url: '/pages/login/login'
          });
          break;
        case 404:
          errorMsg = '请求资源不存在';
          break;
        case 500:
          errorMsg = '服务器错误';
          break;
        default:
          errorMsg = error.message || '请求失败';
      }
    }
    uni.showToast({
      title: errorMsg,
      icon: 'none'
    });
    return Promise.reject(error);
  }
);

// 导出登录API（假设后端路径为/user/login）
export const login = (userData) => service.post('/user/login', userData);

// 导出自动登录API
export const autoLogin = (code) => service.get('/user/autoLogin', { params: { code } });

// 导出根据身份证获取用户头像API
export const getUserAvatar = (idCard) => service.get('/user/getUserAvatar', { params: { idCard } });

// 导出API方法
export const fetchData = () => service.get('/data');
export const submitData = (data) => service.post('/submit', data);
export const fetchUsers = () => service.get('/users');
export const createUser = (userData) => service.post('/users', userData);

export default service;